package com.weiaibenpao.demo.chislim.ui.activity.running;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.UMShareAPI;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.api.Url;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.bean.SportOverInfoBean;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.LoadingDialogUtils;
import com.weiaibenpao.demo.chislim.utils.ShareUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class ShareActivity extends BaseActivity {
    public static final String URL = "url";

    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.mid_text)
    TextView midText;
    @BindView(R.id.share_dialog_layout)
    View shareDialogLayout;
    @BindView(R.id.tv_new)
    TextView tvNew;
    @BindView(R.id.img_grade)
    ImageView imgGrade;
    @BindView(R.id.tv_marathon_title)
    TextView tvMarathonTitle;
    @BindView(R.id.tv_next_grade)
    TextView tvNextGrade;
    @BindView(R.id.layout_detail)
    LinearLayout layoutDetail;
    private String sportType;
    private SportOverInfoBean infoBean;
    private String provinceName;
    private boolean isBadge, isGrade, isMarathon, isChina;
    private ArrayList<String> list;
    private ShareUtils shareUtils;
    private String badgeName = "恭喜获得新的荣誉勋章";
    private String gradeName = "恭喜获得新的等级";
    private String marathonName = "恭喜赛事已完成";
    private String chinaName = "恭喜中国跑已完成";
    private String mUrl;
    private int index;
    private LoadingDialogUtils.Builder dialog;
    private int type=1;

    /**
     * @param context
     * @param sportOverInfoBean
     * @param sportType         常规 行政 趣味  ·室内/外
     * @param province          是中国跑就传区域名字，否则为空
     */
    public static void startSelf(Context context, SportOverInfoBean sportOverInfoBean, String sportType, String province) {
        Intent intent = new Intent(context, ShareActivity.class);
        intent.putExtra(Constant.CLASS_BEAN, sportOverInfoBean);
        intent.putExtra(Constant.SPORT_TYPE, sportType);
        intent.putExtra(Constant.PROVINCE, province);

        context.startActivity(intent);

    }

    public static void startSelf(Context context, String url,String sportType) {
        Intent intent = new Intent(context, ShareActivity.class);
        intent.putExtra(URL, url);
        intent.putExtra(Constant.SPORT_TYPE, sportType);
        context.startActivity(intent);
    }


    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_share;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        infoBean = ((SportOverInfoBean) getIntent().getSerializableExtra(Constant.CLASS_BEAN));

        mUrl=infoBean!=null?infoBean.getUrl():getIntent().getStringExtra(URL);
        provinceName = getIntent().getStringExtra(Constant.PROVINCE);
        sportType = getIntent().getStringExtra(Constant.SPORT_TYPE);
        midText.setText(sportType);
        Logger.e("sportType=="+sportType);

        //分享
        shareUtils = new ShareUtils(this);
        if(infoBean != null) {
            isShowDialog();

        }
        initWebView();

    }


    private void initWebView() {
        dialog = new LoadingDialogUtils.Builder(this);
        dialog.setTitle("正在加载...").show();
        //设置相关属性
        /**
         * WebSettings用来设置WebView的相关属性
         */
        WebSettings webSettings = webView.getSettings();
        //设置WebView支持JavaScript
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        /**
         * 判断页面加载过程
         * 当网络加载缓慢,我们可以再页面加载出来之前设置显示进度条
         * setWebChromeClient一般处理加载进度,设置标题,处理js对话框
         */
        webView.setWebChromeClient(new WebChromeClient(){

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

                if(newProgress > 90){     //页面加载完成
                    dialog.dismiss();
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                ShareActivity.this.setTitle(title);           //设置标题
                super.onReceivedTitle(view, title);

            }
        });

        /**
         * WebViewClient帮助webView处理一些页面控制和请求通知
         * 当点击webview控件中的链接时,在这里设置显示在webview中,否则,会在浏览器打开
         */
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url){
                //设置网页在webview控件中打开,false在浏览器中打开
                view.loadUrl(url);
                return true;
            }
        });
        webView.loadUrl(Url.BASE_URL+Url.SERVICE_SPORT+mUrl);


        Logger.e("load url is "+webView.getUrl());
    }

    private void isShowDialog() {
        list = new ArrayList<>();
        if (infoBean.getBadge().getId() > 0) {
            list.add("1");

            isBadge = true;
        }
        if (infoBean.getGrade().getId() > 0) {
            list.add("2");
            isGrade = true;
        }
        if (!TextUtils.isEmpty(infoBean.getChinaFinshImage())) {
            list.add("3");
            isChina = true;
        }
        if (infoBean.getMarathonList()!=null&&infoBean.getMarathonList().size() > 0) {
            isMarathon = true;
            for (int i = 0; i < infoBean.getMarathonList().size(); i++) {
                list.add((4 + i) + "");
            }
        }
        if (isBadge || isGrade || isMarathon || isChina) {
            immersionBar.statusBarDarkFont(false)
                    // .statusBarColor(R.color.white)//状态栏颜色，不写默认透明色
                    .fitsSystemWindows(false)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                    .init();
            shareDialogLayout.setVisibility(View.VISIBLE);
            if (isBadge) {
                getBadge();
            } else if (isGrade) {
                getGrade();
            } else if (isMarathon) {
                getMarathon(0);
            } else if (isChina) {
                getChina();
            }
        }
    }


    /**
     * 分享弹框
     * @param title
     * @param achiveImage
     * @param firstMark
     * @param secondMark
     * @return
     */
    private String getShareUrl(String title, String achiveImage, String firstMark, String secondMark) {
        return "malasong/achievementShare.html?title=" + title +
                "&achiveImage=" +
                achiveImage +
                "&firstMark=" +
                firstMark +
                "&secondMark=" +
                secondMark;
    }


    /**
     * 中国跑
     */
    private void getChina() {
        layoutDetail.setVisibility(View.VISIBLE);
        tvNextGrade.setVisibility(View.VISIBLE);

        tvNew.setText(chinaName);
        Glide.with(this).load(infoBean.getChinaFinshImage()).into(imgGrade);
        tvMarathonTitle.setText(provinceName);
        tvNextGrade.setText(infoBean.getChinaFinshMark());
    }

    /**
     * 马拉松赛事
     */
    private void getMarathon(int index) {
        layoutDetail.setVisibility(View.VISIBLE);
        tvNextGrade.setVisibility(View.GONE);
        tvNew.setText(marathonName);
        SportOverInfoBean.MarathonListBean marathonListBean = infoBean.getMarathonList().get(index);
        Glide.with(this).load(marathonListBean.getMContent()).into(imgGrade);
        tvMarathonTitle.setText(marathonListBean.getMarathonTitle() + "\n" + marathonListBean.getGroupName());//+ "\\n" + marathonListBean.getGroupName()
//        tvNextGrade.setText(marathonListBean.getGroupName());
    }

    /**
     * 等级
     */
    private void getGrade() {
        layoutDetail.setVisibility(View.VISIBLE);
        tvNew.setText(gradeName);
        Logger.e("getGradeImage==" + infoBean.getGrade().getGradeImage());//http://ow79arwyc.bkt.clouddn.com/奖牌设计中秋节.png

        Glide.with(this).load(infoBean.getGrade().getGradeImage()).into(imgGrade);
        tvMarathonTitle.setText(infoBean.getGrade().getGradeName());
        tvNextGrade.setText("距离达成下一等级还有" + infoBean.getGrade().getRestGrade() + "公里");
    }

    /**
     * 勋章
     */
    private void getBadge() {
        layoutDetail.setVisibility(View.GONE);
        tvNew.setText(badgeName);
        Glide.with(this).load(infoBean.getBadge().getBadgeIconUrl()).into(imgGrade);
    }

    private int count;

    @OnClick({R.id.left_image, R.id.btn_sure, R.id.btn_share,R.id.right_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_image:
                if(webView.canGoBack()){
                    webView.goBack();
                }else {
                    finish();
                }
                break;
            case R.id.right_image:
                type=1;
                checkPerMissions();
                break;
            case R.id.btn_sure:
                count++;
                btnSure();
                break;
            case R.id.btn_share:
                checkPerMissions();
                type=2;

                break;
        }
    }

    @Override
    protected void startDo() {
        super.startDo();
      if (type==2){
          btnShare();
      }else {
          shareUtils.share(mUrl,sportType+" - 跑步数据详情");

      }
    }

    private void btnSure() {
        if (count > list.size() - 1) {
            shareDialogLayout.setVisibility(View.GONE);
            super.initImmersionBar();
        } else {
            String s = list.get(count);
            if (s.equals("1")) {
                getBadge();
            } else if (s.equals("2")) {
                getGrade();
            } else if (s.equals("3")) {
                getChina();
            } else {
                index++;
                if (index < infoBean.getMarathonList().size()) {
                    getMarathon(index);
                }

            }
        }
    }

    private void btnShare() {
        String s = list.get(count);
        if (s.equals("1")) {
            String shareUrl = getShareUrl(badgeName, infoBean.getBadge().getBadgeIconUrl(), "", "");
            shareUtils.share(shareUrl, badgeName);
        } else if (s.equals("2")) {
            String shareUrl = getShareUrl(gradeName, infoBean.getGrade().getGradeImage(), infoBean.getGrade().getGradeName(), "距离达成下一等级还有" + infoBean.getGrade().getRestGrade() + "公里");
            shareUtils.share(shareUrl, gradeName);
        } else if (s.equals("3")) {
            String shareUrl = getShareUrl(chinaName, infoBean.getChinaFinshImage(), provinceName, infoBean.getChinaFinshMark());
            shareUtils.share(shareUrl, chinaName);
        } else {
            String shareUrl = getShareUrl(marathonName, infoBean.getMarathonList().get(index).getMContent(), infoBean.getMarathonList().get(index).getMarathonTitle(), infoBean.getMarathonList().get(index).getGroupName());
            shareUtils.share(shareUrl, marathonName);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        UMShareAPI.get(this).release();
        super.onDestroy();
    }

}
